package core

/*
#cgo CFLAGS: -I../../lib/server
#cgo LDFLAGS: -L../../lib/server -lkeyMouse
#include "keyMouse.h"
*/
import "C"
import (
	"encoding/json"
	"log"
	"screenRobot/network"
	"screenRobot/network/tcp"
)

//export goHandleKey
func goHandleKey(key, flag C.int) {
	keyMouse.updateKey(int(key), toBool(flag))
}

//export goHandleMouse
func goHandleMouse(x, y C.int, lclick, rclick, ldbclick, rdbclick, delta C.int) {
	keyMouse.updateMouse(int(x), int(y), int(lclick), int(rclick), int(ldbclick), int(rdbclick), int(delta))
}
func toBool(val C.int) bool {
	return int(val) == 1
}

type KeyMouse struct {
	DownKey  int //按下按键
	UpKey    int //松开按键
	X        int //鼠标x位置
	Y        int //鼠标y位置
	LClick   int //是否按下
	RClick   int
	LDBClick int
	RDBClick int
	Delta    int
	callback func(mouse *KeyMouse)
}

// 重置
func (k *KeyMouse) reset() {
	//表示没有按下按钮
	k.DownKey = -1
	k.UpKey = -1
	//没有点击状态
	k.LClick = 0
	k.RClick = 0
	k.LDBClick = 0
	k.RDBClick = 0
}

// 更新按键
func (k *KeyMouse) updateKey(key int, flag bool) {
	k.reset()
	if flag {
		k.DownKey = key
	} else {
		k.UpKey = key
	}
	k.marshal()
	k.callback(k)
}

func (k *KeyMouse) marshal() []byte {
	bytes, _ := json.Marshal(k)
	log.Println(string(bytes))
	return bytes
}

// 更新鼠标
func (k *KeyMouse) updateMouse(x, y, lclick, rclick, ldbclick, rdbclick, delta int) {
	k.reset()
	k.X = x
	k.Y = y
	k.LClick = lclick
	k.RClick = rclick
	k.LDBClick = ldbclick
	k.RDBClick = rdbclick
	k.Delta = delta
	k.marshal()
	k.callback(k)
}

var keyMouse = KeyMouse{callback: sendMsg}

// 发送信息
func sendMsg(mouse *KeyMouse) {
	//如果没有客户端连接
	if len(tcp.Clients) == 0 {
		return
	}

	jsonData, _ := json.Marshal(mouse)
	index := 0
	for index < len(tcp.Clients) {
		val := tcp.Clients[index]
		_, err := val.Write(jsonData)
		if network.Handler("发送信息失败", err) {
			val.Close()
			tcp.Clients = append(tcp.Clients[:index], tcp.Clients[index+1:]...)
			//更新值
			tcp.ClientLen <- len(tcp.Clients)
			continue
		}
		index++
	}
}

// Listener 开启监听
func Listener() {
	go C.mouseListenerEvent()
	go C.keyListenerEvent()
}
